package com.lewis.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lewis.core.base.domain.entity.SysDictData;
import com.lewis.core.base.domain.entity.SysDictType;
import com.lewis.core.constant.UserConstants;
import com.lewis.core.exception.CustomException;
import com.lewis.core.utils.DateUtil;
import com.lewis.core.utils.DictUtil;
import com.lewis.core.utils.StringUtil;
import com.lewis.system.mapper.SysDictDataMapper;
import com.lewis.system.mapper.SysDictTypeMapper;
import com.lewis.system.service.ISysDictTypeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 字典 业务层处理
 *
 * @author Lewis
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService {

    @Resource
    private SysDictTypeMapper dictTypeMapper;

    @Resource
    private SysDictDataMapper dictDataMapper;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init() {
        loadingDictCache();
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeList(SysDictType dictType) {

        LambdaQueryWrapper<SysDictType> lqw = new LambdaQueryWrapper<SysDictType>()
                .like(StringUtil.isNotEmpty(dictType.getDictName()), SysDictType::getDictName, dictType.getDictName())
                .like(StringUtil.isNotEmpty(dictType.getDictType()), SysDictType::getDictType, dictType.getDictType())
                .eq(StringUtil.isNotEmpty(dictType.getStatus()), SysDictType::getStatus, dictType.getStatus())
        ;

        Map<String, Object> params = dictType.getParams();
        if (params != null) {
            Object beginTime = dictType.getParams().get("beginTime");
            if (beginTime != null) {
                lqw.ge(StringUtil.isNotEmpty(String.valueOf(DateUtil.parseDate(dictType.getParams().get("beginTime")))), SysDictType::getCreateTime, String.valueOf(DateUtil.parseDate(dictType.getParams().get("beginTime"))));
            }
            Object endTime = dictType.getParams().get("endTime");
            if (endTime != null) {
                lqw.le(StringUtil.isNotEmpty(String.valueOf(DateUtil.parseDate(dictType.getParams().get("endTime")))), SysDictType::getCreateTime, String.valueOf(DateUtil.parseDate(dictType.getParams().get("endTime"))));
            }
        }

        return dictTypeMapper.selectList(lqw);
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        List<SysDictData> dictDatas = DictUtil.getDictCache(dictType);
        if (StringUtil.isNotEmpty(dictDatas)) {
            return dictDatas;
        }
        dictDatas = this.selectDictDataByType(dictType);
        if (StringUtil.isNotEmpty(dictDatas)) {
            DictUtil.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }

    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     * @return 结果
     */
    @Override
    public void deleteDictTypeByIds(Long[] dictIds) {
        for (Long dictId : dictIds) {
            SysDictType dictType = dictTypeMapper.selectOne(
                    new LambdaQueryWrapper<SysDictType>()
                            .eq(SysDictType::getDictId, dictId)
            );
            if (dictDataMapper.selectCount(
                    new LambdaQueryWrapper<SysDictData>()
                            .eq(SysDictData::getDictType, dictType.getDictType())
            ) > 0) {
                throw new CustomException(String.format("%1$s已分配,不能删除" , dictType.getDictName()));
            }
            dictTypeMapper.delete(
                    new LambdaQueryWrapper<SysDictType>()
                            .eq(SysDictType::getDictId, dictId)
            );
            DictUtil.removeDictCache(dictType.getDictType());
        }
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache() {
        List<SysDictType> dictTypeList = dictTypeMapper.selectList(new LambdaQueryWrapper<>());
        for (SysDictType dictType : dictTypeList) {
            List<SysDictData> dictDatas = this.selectDictDataByType(dictType.getDictType());
            DictUtil.setDictCache(dictType.getDictType(), dictDatas);
        }
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache() {
        DictUtil.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    public boolean save(SysDictType dict) {
        int row = dictTypeMapper.insert(dict);
        if (row > 0) {
            DictUtil.setDictCache(dict.getDictType(), null);
        }
        return row == 1;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDictType(SysDictType dict) {
        SysDictType oldDict = dictTypeMapper.selectOne(
                new LambdaQueryWrapper<SysDictType>()
                        .eq(SysDictType::getDictId, dict.getDictId())
        );

        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(dict.getDictType());
        dictDataMapper.update(
                sysDictData,
                new LambdaUpdateWrapper<SysDictData>()
                        .eq(SysDictData::getDictType, oldDict.getDictType())
        );
        int row = dictTypeMapper.update(
                dict,
                new LambdaUpdateWrapper<SysDictType>()
                        .eq(SysDictType::getDictId, dict.getDictId())
        );
        if (row > 0) {
            List<SysDictData> dictDatas = this.selectDictDataByType(dict.getDictType());
            DictUtil.setDictCache(dict.getDictType(), dictDatas);
        }
        return row;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public String checkDictTypeUnique(SysDictType dict) {
        Long dictId = StringUtil.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        SysDictType dictType = dictTypeMapper.selectOne(
                new LambdaQueryWrapper<SysDictType>()
                        .eq(SysDictType::getDictType, dict.getDictType())
                        .last("limit 1")
        );
        if (StringUtil.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
